package com.example.recyclerview2;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class FruitAdpater extends RecyclerView.Adapter<FruitAdpater.ViewHolder> {
    private List<Fruit> mFruitList;


    static class ViewHolder extends RecyclerView.ViewHolder {
        //点击事件：d
        View fruieView;


        ImageView fruitImage;
        TextView fruitName;

        public ViewHolder(@NonNull View view) {
            super(view);

            //d:
            fruieView = view;


            fruitImage = (ImageView) view.findViewById(R.id.image_item);
            fruitName = (TextView) view.findViewById(R.id.tv_item);
        }
    }

    public FruitAdpater(List<Fruit> mFruitList) {
        this.mFruitList = mFruitList;
    }

    @NonNull
    @Override
    //创建实例
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item, parent, false);

        //d:
        final  ViewHolder holder = new ViewHolder(view);
        holder.fruieView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                Fruit fruit = mFruitList.get(position);
                Toast.makeText(v.getContext(), "you clicked view" + fruit.getName(), Toast.LENGTH_SHORT).show();
            }
        });
        holder.fruitImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                Fruit fruit = mFruitList.get(position);
                Toast.makeText(v.getContext(), "you clicked imag" +fruit.getName(), Toast.LENGTH_SHORT).show();
            }
        });

//        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    //对子项数据进行赋值
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        Fruit fruit = mFruitList.get(position);
        holder.fruitImage.setImageResource(fruit.getImageId());
        holder.fruitName.setText(fruit.getName());
    }

    @Override
    public int getItemCount() {
        return mFruitList.size();
    }


}
